package com.tanhua.app.controllerservice;

import cn.hutool.core.io.FileUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.SoundApi;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Sound;
import com.tanhua.domain.vo.SoundVo;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.apache.dubbo.config.annotation.Reference;
import static org.springframework.http.ResponseEntity.ok;
import static org.springframework.http.ResponseEntity.status;

@Service
public class SoundService {
    @Reference
    private SoundApi soundApi;
    @Reference
    private UserInfoApi userInfoApi;
    private final FastFileStorageClient fastFileStorageClient;
    private final FdfsWebServer fdfsWebServer;

    public SoundService(
            @Autowired FastFileStorageClient fastFileStorageClient,
            @Autowired FdfsWebServer fdfsWebServer
    ) {
        this.fastFileStorageClient = fastFileStorageClient;
        this.fdfsWebServer = fdfsWebServer;
    }

    public ResponseEntity<String> send(MultipartFile soundFile, Long userId) throws IOException {
        // 将传音文件上传到FastDFS
        final StorePath storePath = fastFileStorageClient.uploadFile(
                soundFile.getInputStream(),
                soundFile.getSize(),
                FileUtil.extName(soundFile.getOriginalFilename()),
                null
        );
        final String fullPath = storePath.getFullPath();
        final String soundUrl = fdfsWebServer.getWebServerUrl() + fullPath;

        // 构造 Sound 对象
        final Sound sound = new Sound(
                userId,
                soundUrl,
                fullPath
        );

        // 在Mongo中添加一条记录
        soundApi.send(sound);

        return ok("传音发送成功");
    }

    public ResponseEntity<SoundVo> receive(Long userId) {
        // 从Mongo中随机取一条传音记录，方法内实现了随取随删
        final Sound sound = soundApi.receive(userId);

        // Mongo中没有传音文件
        if (sound == null) {
            return status(500).body(new SoundVo(0L, "", "", "", 0, "", 0));
        }

        // 封装返回结果
        final UserInfo userInfo = userInfoApi.findUserInfo(sound.getUserId());
        final SoundVo soundVo = new SoundVo(
                sound.getUserId(),
                userInfo.getAvatar(),
                userInfo.getNickname(),
                userInfo.getGender(),
                userInfo.getAge(),
                sound.getSoundUrl(),
                soundApi.getRemainingTimesByUserId(sound.getUserId())
        );

        // 从FastDFS中删除文件
        fastFileStorageClient.deleteFile(sound.getSoundPath());

        return ok(soundVo);
    }
}
